<template>
  <div class="contract-list-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入合同名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 合同列表表格 -->
    <el-table 
      :data="contractList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="contract_name" label="合同名称" min-width="200px"></el-table-column>
      <el-table-column prop="companyName" label="企业名称" min-width="200px"></el-table-column>
      <el-table-column prop="customer_name" label="客户名称" width="150px"></el-table-column>
      <el-table-column prop="customer_phone" label="手机号" width="130px"></el-table-column>
      <el-table-column prop="cost" label="合同金额" width="120px" align="center">
        <template slot-scope="scope">
          ¥{{ formatMoney(scope.row.cost) }}
        </template>
      </el-table-column>
      <el-table-column prop="payment_status" label="付款状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.payment_status === 1 ? 'success' : 'warning'">
            {{ scope.row.payment_status === 1 ? '已付款' : '未付款' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="payment_time" label="付款时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.payment_time) }}
        </template>
      </el-table-column>
        <el-table-column prop="remark" label="合同备注" max-width="150px" show-overflow-tooltip></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="update_time" label="更新时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.update_time) }}
        </template>
      </el-table-column> -->
       <el-table-column label="合同凭证" width="100px" align="center">
         <template slot-scope="scope">
           <el-button 
             v-if="scope.row.img_url" 
             type="text" 
             size="small" 
             @click="handleViewImage(scope.row.img_url)"
           >
             查看凭证
           </el-button>
           <span v-else style="color: #999;">无凭证</span>
         </template>
       </el-table-column>
       <el-table-column label="操作" width="180px" align="center">
         <template slot-scope="scope">
           <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
           <el-button type="text" size="small" @click="handleGenerateOrder(scope.row)" style="margin-left: 10px;">生成订单</el-button>
           <el-button type="text" size="small" @click="handleViewOrders(scope.row)" style="margin-left: 10px;">查看订单</el-button>
         </template>
       </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 合同凭证图片预览弹窗 -->
    <el-dialog
      title="合同凭证"
      :visible.sync="imageDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div class="image-preview-container">
        <el-image 
          v-for="(url, idx) in currentImageUrls"
          :key="url"
          :src="url"
          style="width: 100%; max-height: 500px; margin-bottom: 10px;"
          fit="contain"
          :preview-src-list="currentImageUrls"
          :initial-index="idx"
          lazy
        >
          <div slot="placeholder" class="image-slot">
            <i class="el-icon-loading"></i>
            <p>图片加载中...</p>
          </div>
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <p>图片加载失败</p>
            <!-- <p style="font-size: 12px; margin-top: 5px;">{{ currentImageUrl }}</p> -->
          </div>
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imageDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="openImageInNewTab">在新窗口打开</el-button>
      </div>
    </el-dialog>

    <!-- 生成订单产品选择弹窗 -->
    <el-dialog
      title="选择产品生成订单"
      :visible.sync="orderDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      center
    >
      <div class="product-selection-container">
        <div class="contract-info">
          <h4>合同信息</h4>
          <p><strong>合同名称：</strong>{{ currentContract.contract_name }}</p>
          <p><strong>客户名称：</strong>{{ currentContract.companyName }}</p>
        </div>
        
        <div class="product-list">
          <h4>产品列表</h4>
          <div v-for="product in productList" :key="product.id" class="product-item">
            <div class="product-header">
              <el-checkbox 
                v-model="product.selected" 
                @change="handleProductChange(product)"
              >
                <strong>{{ product.device_name }}</strong>
              </el-checkbox>
              <el-tag v-if="product.is_need" type="warning" size="mini">需要流量卡</el-tag>
              <el-tag v-else type="info" size="mini">无需流量卡</el-tag>
            </div>
            
            <div class="factory-info">
              <span><strong>工厂：</strong>{{ product.factory.factory_name }}</span>
              <span><strong>地址：</strong>{{ product.factory.address }}</span>
            </div>
            
            <div class="accessories-list" v-if="product.selected">
              <h5>配件列表：</h5>
              <div class="accessories-grid">
                <el-checkbox 
                  v-for="accessory in product.accessories" 
                  :key="accessory.id"
                  v-model="accessory.selected"
                  @change="handleAccessoryChange"
                >
                  {{ accessory.accessory_name }}
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrderGeneration" :loading="orderLoading">生成订单</el-button>
      </div>
    </el-dialog>

    <!-- 查看订单弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="ordersDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      center
    >
      <div class="orders-container">
        <div class="contract-info">
          <h4>合同信息</h4>
          <p><strong>合同编号：</strong>{{ currentContractForOrders.contract_name }}</p>
          <p><strong>公司名称：</strong>{{ currentContractForOrders.companyName }}</p>
        </div>
        
        <div class="orders-list" v-loading="ordersLoading">
          <h4>订单列表</h4>
          <el-table :data="ordersList" style="width: 100%" border>
            <!-- <el-table-column label="订单ID" prop="id" width="80" align="center"></el-table-column> -->
            <el-table-column label="设备信息" width="150" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.devices.device_name }}</div>
                <!-- <div style="font-size: 12px; color: #999;">ID: {{ scope.row.devices.id }}</div> -->
              </template>
            </el-table-column>
            <el-table-column label="工厂信息" width="200" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.factory.factory_name }}</div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.factory.address }}</div>
              </template>
            </el-table-column>
            <el-table-column label="配件信息" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.accessories && scope.row.accessories.length > 0">
                  <el-tag 
                    v-for="accessory in scope.row.accessories" 
                    :key="accessory.id"
                    size="mini"
                    style="margin: 2px;"
                  >
                    {{ accessory.accessory_name }}
                  </el-tag>
                </div>
                <div v-else style="color: #999; font-size: 12px;">无配件</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="getStatusType(scope.row.status)" 
                  size="mini"
                >
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="物流单号" width="150" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.track_number">{{ scope.row.track_number }}</span>
                <span v-else style="color: #999;">暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="160" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
                <span v-else style="color: #999;">暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button 
                  type="text" size="small"
                  @click="handleDeleteOrder(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="ordersDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getContractList, getProductList, generateOrder, getOrdersByContractId, deleteOrder } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';
import { baseURLs } from '@/utils/request';

export default {
  name: 'ContractManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 列表相关
      contractList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 图片预览弹窗相关
      imageDialogVisible: false,
      currentImageUrls: [], // 支持多张图片
      
      // 生成订单弹窗相关
      orderDialogVisible: false,
      orderLoading: false,
      currentContract: {},
      productList: [],
      
      // 查看订单弹窗相关
      ordersDialogVisible: false,
      ordersLoading: false,
      currentContractForOrders: {},
      ordersList: []
    }
  },
  mounted() {
    this.fetchContractList();
  },
  methods: {
    // 获取合同列表
    async fetchContractList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }
        
        const response = await getContractList(params);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.contractList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取合同列表失败');
        }
      } catch (error) {
        console.error('获取合同列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取合同列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchContractList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchContractList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchContractList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchContractList();
    },
    
    // 查看合同凭证图片（支持多张图片，分号分隔）
    handleViewImage(imageUrl) {
      if (imageUrl) {
        this.currentImageUrls = imageUrl.split(';').filter(Boolean);
      } else {
        this.currentImageUrls = [];
      }
      this.imageDialogVisible = true;
    },
    
    // 在新窗口打开所有图片
    openImageInNewTab() {
      if (this.currentImageUrls && this.currentImageUrls.length) {
        this.currentImageUrls.forEach(url => {
          window.open(url, '_blank');
        });
      }
    },
    
    // 修改合同
    handleEdit(row) {
      // TODO: 实现合同修改功能
      this.$message.info('合同修改功能待实现');
    },
    
    // 生成订单
    handleGenerateOrder(row) {
      this.currentContract = row;
      this.orderDialogVisible = true;
      this.loadProductList();
    },
    
    // 加载产品列表
    async loadProductList() {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await getProductList();
        
        if (response.data && response.data.code === 1) {
          // 处理产品数据，添加选择状态
          this.productList = response.data.data.map(product => ({
            ...product,
            selected: false,
            accessories: product.accessories.map(accessory => ({
              ...accessory,
              selected: false
            }))
          }));
        } else {
          this.$message.error(response.data.msg || '获取产品列表失败');
        }
      } catch (error) {
        console.error('获取产品列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取产品列表失败');
        }
      }
    },
    
    // 处理产品选择变化
    handleProductChange(product) {
      // 如果取消选择产品，同时取消选择所有配件
      if (!product.selected) {
        product.accessories.forEach(accessory => {
          accessory.selected = false;
        });
      }
    },
    
    // 处理配件选择变化
    handleAccessoryChange() {
      // 可以在这里添加配件选择的逻辑
    },
    
    // 提交订单生成
    async submitOrderGeneration() {
      try {
        // 检查是否选择了产品
        const selectedProducts = this.productList.filter(product => product.selected);
        if (selectedProducts.length === 0) {
          this.$message.warning('请至少选择一个产品');
          return;
        }
        
        // 收集选中的设备ID和配件ID
        const devices_id = selectedProducts.map(product => product.id);
        const accessories_id = [];
        
        selectedProducts.forEach(product => {
          product.accessories.forEach(accessory => {
            if (accessory.selected) {
              accessories_id.push(accessory.id);
            }
          });
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        this.orderLoading = true;
        
        const orderData = {
          devices_id: devices_id,
          accessories_id: accessories_id,
          contract_id: this.currentContract.id,
          customer_id: this.currentContract.customer_id
        };
        
        console.log('生成订单数据:', orderData);
        
        const response = await generateOrder(orderData);
        
        if (response.data && response.data.code === 1) {
          this.$message.success(`成功生成 ${response.data.order_count} 个订单`);
          this.orderDialogVisible = false;
          // 可以跳转到订单管理页面
          // this.$router.push('/order-management');
        } else {
          this.$message.error(response.data.msg || '生成订单失败');
        }
      } catch (error) {
        console.error('生成订单失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('生成订单失败');
        }
      } finally {
        this.orderLoading = false;
      }
    },
    
    // 查看订单
    async handleViewOrders(contract) {
      this.currentContractForOrders = contract;
      this.ordersDialogVisible = true;
      this.ordersLoading = true;
      
      try {
        const response = await getOrdersByContractId(contract.id);
        if (response.data && response.data.code === 1) {
          this.ordersList = response.data.data || [];
        } else {
          this.$message.error(response.data.msg || '获取订单列表失败');
          this.ordersList = [];
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        this.$message.error('获取订单列表失败');
        this.ordersList = [];
      } finally {
        this.ordersLoading = false;
      }
    },
    
    // 删除订单
    async handleDeleteOrder(order) {
      try {
        await this.$confirm(`确定要删除该订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 调用删除订单API
        const response = await deleteOrder(order.id);
        
        if (response.data && response.data.code === 1) {
          this.$message.success('删除订单成功');
          // 重新加载订单列表
          this.handleViewOrders(this.currentContractForOrders);
        } else {
          this.$message.error(response.data.msg || '删除订单失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除订单失败:', error);
          this.$message.error('删除订单失败');
        }
      }
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'warning',   // 生产中
        2: 'success',   // 已发货
        3: 'info'       // 已签收
      };
      return statusMap[status] || 'info';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '生产中',
        2: '已发货',
        3: '已签收'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return '-';
      return new Date(timestamp * 1000).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    
    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00';
      return parseFloat(amount).toFixed(2);
    }
  }
}
</script>

<style scoped>
.contract-list-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 4px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-descriptions {
  margin-top: 20px;
}

.el-descriptions-item__label {
  font-weight: bold;
  background-color: #f5f7fa;
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.image-slot p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
}

/* 产品选择弹窗样式 */
.product-selection-container {
  max-height: 600px;
  overflow-y: auto;
}

.product-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #67c23a;
  padding-bottom: 5px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
}

.product-item:hover {
  border-color: #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.1);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.factory-info {
  margin-bottom: 10px;
  color: #606266;
  font-size: 13px;
}

.factory-info span {
  margin-right: 20px;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

/* 查看订单弹窗样式 */
.orders-container {
  max-height: 1000px;
  overflow-y: auto;
}

.orders-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

/* 产品选择弹窗样式 */
.product-selection-container {
  max-height: 600px;
  overflow-y: auto;
}

.contract-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.contract-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.contract-info p {
  margin: 5px 0;
  color: #606266;
}

.product-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: #fff;
}

.product-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.product-header .el-checkbox {
  margin-right: 10px;
}

.factory-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.factory-info span {
  display: block;
  margin-bottom: 5px;
  color: #606266;
  font-size: 13px;
}

.accessories-list {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

.accessories-list h5 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

.accessories-grid .el-checkbox {
  margin-right: 0;
}



.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
  border-radius: 4px;
}

.image-slot p {
  margin: 10px 0 0 0;
  font-size: 14px;
}
</style>